/**
 * 静态分析单个规则接口测试
 *
 * Created by nongzhizhong on 2022/08/11.
 */
const chai = require('chai');
chai.use(require('chai-http'));
// eslint-disable-next-line no-unused-vars
const should = chai.should();
const randomstring = require('randomstring');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
module.exports = describe('/GET /static-analyze/rules/:ruleId.json', function () {
  const administrator = new Administrator();
  let newUser;
  let ruleSets;
  let rules;

  function getRandomRules(num) {
    if (!rules || !rules.length) {
      return [];
    }
    const chance = num / rules.length;
    let arr = [];
    for (let i = 0; i < rules.length && arr.length < num; i += 1) {
      const gap = num - arr.length;
      const left = rules.length - i;
      if (left <= gap) {
        arr = arr.concat(rules.slice(i));
        break;
      }
      if (Math.random() < chance) {
        arr.push(rules[i]);
      }
    }
    return arr;
  }

  before(async function () {
    await administrator.login();
    newUser = await administrator.createRandomTester();
    ruleSets = await newUser.getRules();
    rules = ruleSets
      .reduce((arr, { levels }) => arr.concat(levels
        .reduce((arr1, { rules: lvlRules }) => arr1.concat(lvlRules), [])), []);
  });
  after(async function () {
    await administrator.removeUsers([newUser.userId]);
  });
  // 获取每一个规则
  it('it should rule by ruleId', function (done) {
    const rule = getRandomRules(1)[0];
    chai.request(uri)
      .get(`/static-analyze/rules/${rule.ruleId}.json`)
      .set('Authorization', `Bearer ${newUser.token.accessToken}`)
      .end((err, res) => {
        res.should.have.status(200);
        const resRule = {
          ruleCode: res.body.ruleCode,
          ruleName: res.body.name,
          ruleId: res.body.ruleId,
          originalLevel: res.body.originalLevel,
          orderIndex: res.body.orderIndex,
        };
        chai.assert.deepEqual(resRule, rule);
        done();
      });
  });
  // 获取一个不存在的规则
  it('it should empty list by ruleId not found', function (done) {
    const ruleId = randomstring.generate({ length: 24, charset: 'hex' });
    chai.request(uri)
      .get(`/static-analyze/rules/${ruleId}.json`)
      .set('Authorization', `Bearer ${newUser.token.accessToken}`)
      .end((err, res) => {
        res.should.have.status(404);
        done();
      });
  });
});
